<template>
    <view class="container">
      <view class="brand">
        <view class="logo">
          <up-image :showLoading="true" radius="80" :src="siteInfo.logo" width="80px" height="80px" />
        </view>
        <view class="content">
          <view class="title">{{ siteInfo.title }}</view>
        </view>
      </view>
      <view class="form">
        <view class="tips">
          <view class="text">登录后享受更多精彩内容</view>
        </view>
        <view class="btn-group">
          <view class="btn">
            <up-button @tap="hanldLoginOpenid" :color="`linear-gradient(180deg, ${siteInfo.theme_color} 0%, ${siteInfo.theme_active_color} 100%)`" shape="circle"
              text="立即授权登录"></up-button>
          </view>
          <view class="btn" @tap="onBackPage">
            <up-button shape="circle" text="暂不登录"></up-button>
          </view>
        </view>
      </view>
      <!-- 登录授权 -->
      <view class="modal">
        <u-popup :round="10" :show="is_popup" :closeable="true">
          <form catchreset="formReset">
            <view class="user">
              <view class="header">
                <view class="left">
                  <view class="logo">
                    <u-image radius="24" :showLoading="true" :src="siteInfo.logo" width="24px" height="24px" />
                  </view>
                  <view class="title">{{ siteInfo.title }}</view>
                </view>
              </view>
              <view class="remarks">
                <view class="title">设置您的头像、昵称</view>
                <view class="desc">用于展示用户信息</view>
              </view>
              <view class="info">
                <button class="item" open-type="chooseAvatar" @chooseavatar="hanldAvatar">
                  <view class="label">用户头像</view>
                  <view class="value">
                    <image :src="formData.headimg" v-if="formData.headimg" class="avatar" />
                    <text v-else>点此设置微信头像</text>
                  </view>
                </button>
                <button class="item" open-type="getPhoneNumber" @getphonenumber="hanldMobile">
                  <view class="label">手机号码</view>
                  <view class="value">
                    <text v-if="formData.username">已授权</text>
                    <text v-else>点击获取手机号码</text>
                  </view>
                </button>
                <view class="item">
                  <view class="label">用户昵称</view>
                  <view class="value">
                    <view class="nickname">
                      <input placeholder-class="placeholder" style="text-align: right" type="nickname" name="nickname"
                        placeholder="点此输入微信昵称" @change="hanldNickname" />
                    </view>
                    <view class="arrow-right"></view>
                  </view>
                </view>
              </view>
              <view class="start">
                <view class="btn refuse">
                  <u-button throttleTime="3" color="#f4f4f5" text="拒绝" @tap="is_popup = false"></u-button>
                </view>
                <view class="btn">
                  <button style="margin: 0 0; background-color: #19be6b;color:#fff;" @tap="doLogin">
                    确认
                  </button>
                </view>
              </view>
            </view>
          </form>
        </u-popup>
      </view>
      <!-- 版权说明 -->
      <view class="copyright">
        <view class="text">© 2019-2023 Copyright {{ siteInfo.title }}</view>
        <view class="text link" v-if="siteInfo.page_title?.user_service_xieyi && siteInfo.page_title?.user_yinsi_xieyi">
          <u-checkbox-group placement="row" @change="hanldXieyiChange">
            <view class="copyright-active">
              <u-checkbox label="我已阅读并同意" name="1" labelSize="10">
              </u-checkbox>
              <text class="text-link" @tap="openWin({ url: '#tags?name=user_service_xieyi' })">
                《{{ siteInfo.page_title?.user_service_xieyi }}》
              </text>
              与
              <text class="text-link" @tap="openWin({ url: '#tags?name=user_yinsi_xieyi' })">
                《{{ siteInfo.page_title?.user_yinsi_xieyi }}》
              </text>
            </view>
          </u-checkbox-group>
        </view>
      </view>
    </view>
  </template>
    
  <script lang="ts" setup>
  import { upload } from "@/common/upload";
  import { useSite } from "@/stores/site";
  import { openWin, toast } from "@/utils/helpers";
  // 授权登录流程：点击授权登录 - 获取用户code换取用户信息（登录），然后弹窗补充头像和昵称，确认更新用户信息
  const is_popup = ref(false);
  const redirectPath = ref("");
  const siteInfo = storeToRefs(useSite()).siteInfo
  
  const xieyiActive = ref(false)
  const formData = ref({
    openid: '',
    username: '',
    nickname: '',
    headimg: '',
  })
  
  // 提交登录
  const doLogin = () => {
    if (!formData.value.openid) {
      toast("微信唯一参数错误");
      return;
    }
    if (!formData.value.headimg) {
      toast("请上传头像");
      return;
    }
    if (!formData.value.username) {
      toast("请授权手机号");
      return;
    }
    if (!formData.value.nickname) {
      toast("请填写或获取昵称");
      return;
    }
    uni.$u.http.post("Users/login", formData.value).then((e: any) => {
      if ([0, 404].includes(e?.code)) {
        toast(e?.msg || '登录失败')
        return;
      }
      if (!e?.token) {
        toast(e?.token || '登录失败，令牌桶错误')
        return;
      }
      is_popup.value = false;
      uni.setStorageSync("token", e.token);
      uni.$emit("user::update");
      toast('登录成功')
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    });
  };
  
  // 获取openid并显示授权登录框
  const hanldLoginOpenid = () => {  
    if (xieyiActive.value !== true) {
      toast("请同意协议");
      return;
    }
    uni.showLoading({
      title: '加载中',
    });
    uni.login({
      success: (e: any) => {
        const code = e?.code
        uni.$u.http.get('Users/getCodeOpenid', { params: { code } }).then((res: any) => {
          const openid = res?.openid ?? ''
          formData.value.openid = openid;
          is_popup.value = true;
        })
      },
      fail: (e: any) => {
        console.log('微信登录方法失败', e);
      },
      complete: () => {
        uni.hideLoading();
      },
    })
  }
  
  // 获取微信小程序头像
  const hanldAvatar = (e: any) => {
    const filePath = e?.detail?.avatarUrl ?? ''
    upload(filePath, 'avatar').then((url: string) => {
      formData.value.headimg = url
    })
  }
  // 获取手机号码
  const hanldMobile = (e: any) => {
    const code = e?.detail?.code ?? '';
    uni.$u.http.get("Users/getPhoneNumber", { params: { code } }).then((res: any) => {
      formData.value.username = res?.mobile ?? '';
    })
  }
  // 用户昵称
  const hanldNickname = (e: any) => {
    formData.value.nickname = e?.detail?.value ?? '';
  }
  
  // 同意协议
  const hanldXieyiChange = (e: any) => {
    const xieyiValue = e[0] ?? false;
    xieyiActive.value = xieyiValue === '1' ? true : false;
  }
  
  const onBackPage = () => {
    uni.navigateBack()
  };
  
  onLoad((e) => {
    redirectPath.value = e?.redirect || "/pages/index/index";
  });
  </script>
    
  <style lang="scss">
  .modal {
    .user {
      width: 86%;
      margin: 0 auto;
      padding: 30rpx 0rpx;
  
      .info {
        .item {
          display: flex;
          justify-content: space-between;
          font-size: 26rpx !important;
          color: #666 !important;
          padding: 10rpx 0 !important;
          background-color: transparent !important;
          border-radius: 0 !important;
          box-sizing: inherit;
          margin-top: 20rpx !important;
  
          .label {}
  
          .value {
            .avatar {
              width: 60rpx;
              height: 60rpx;
            }
          }
  
          &::after {
            border: 0 !important;
          }
        }
      }
  
      .start {
        display: flex;
        flex-direction: row;
        justify-content: center;
        margin-top: 50rpx;
  
        .btn {
          width: 40%;
          margin: 0rpx 15rpx;
  
          .u-button {
            height: 92rpx;
          }
        }
  
        .refuse {
          .u-button {
            color: #19be6b !important;
          }
        }
      }
  
      .remarks {
        margin: 50rpx 0rpx;
  
        .title {
          font-size: 32rpx;
          font-weight: bold;
        }
  
        .desc {
          color: #909399;
          margin-top: 15rpx;
        }
      }
  
      .header {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
  
        .left {
          display: flex;
          flex-direction: row;
          align-items: center;
  
          .title {
            margin-left: 15rpx;
            color: #303133;
          }
        }
      }
    }
  }
  
  .brand {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 320rpx;
  
    .content {
      display: flex;
      flex-direction: column;
      align-items: center;
  
      .title {
        font-size: 42rpx;
        font-weight: bolder;
        margin: 30rpx 0rpx;
        color: #303133;
      }
  
      .small {
        font-size: 28rpx;
        color: #bababa;
      }
    }
  }
  
  .form {
    width: 80%;
    margin: 30rpx auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  
    .tips {
      margin: 30rpx 0rpx;
      color: #909399;
      font-size: 24rpx;
    }
  
    .btn-group {
      width: 100%;
  
      .btn {
        margin-bottom: 15rpx;
  
        .u-button {
          height: 100rpx;
        }
      }
    }
  }
  
  /* 版权 */
  .copyright {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    margin-top: 30rpx;
  
    .text {
      font-size: 20rpx;
      color: #bababa;
    }
  
    .link {
      margin-top: 30rpx;
      display: flex;
      align-items: center;
  
      .text {
        color: blue;
      }
    }
  }
  
  .copyright-active {
    display: flex;
    align-items: center;
    font-size: 22rpx;
  
    .text-link {
      color: #2979FF;
    }
  }
  </style>
    